package com.test.bxm.utils;


import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class ParamEncodeUtils {

    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("cc","ccc");
        map.put("dd","ddd");
        map.put("a","aaaa");
        map.put("ff","fff");
        map.put(null,"ff");
        map.put("hh",null);
        System.out.println(map);
        System.out.println(sortMap(map));
//        System.out.println(getMd5Key(null,null));
    }


    public static  Map<String,Object> sortMap(Map<String,Object> param){
        if(null == param || param.size() == 0){
            return new TreeMap<>();
        }
        param.remove(null);
        Map<String,Object> rs = new TreeMap<>(param);
        return rs;
    }

    public static String getMd5Key(Map<String,Object> param,String client_secret){

        try {
            Map<String, Object> newParam = sortMap(param);
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            StringBuilder sb = new StringBuilder();
            sb.append(client_secret);
            for(Map.Entry entry:newParam.entrySet()){

                sb.append(entry.getKey().toString());
                sb.append(entry.getValue().toString());
            }
            sb.append(client_secret);

            // 计算md5函数
//            md.update("testSecretaccess_tokenasd78172s8ds9a921j9qqwda12312w1w21211client_id1data_typeXMLorder_status1page1page_size10timestamp1480411125typepdd.order.number.list.gettestSecret".getBytes());
            md.update(sb.toString().getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
